'''
Created on Oct 13, 2012

@author: raygomez
'''

from AVP import AVP
from Error import InvalidAVPLengthError
from Error import InvalidAVPValueError
import struct

class Float32AVP(AVP):
    """32-bit floating point AVP"""
    
    def __init__(self, code, value, vendorId=0):
        AVP.__init__(self, code, struct.pack("!f", value), vendorId)
    
    def getValue(self):
        return struct.unpack("!f", self.payload)[0]

    def setValue(self, value):
        self.payload = struct.pack("!f", value)
        
    def __str__(self):
        return str(self.code) + ":" + str(self.getValue())
    
    @staticmethod
    def convert(avp):
        """Convert generic AVP to Float32
        Raises: InvalidAVPLengthError, InvalidAVPValueError
        """
        if len(avp.payload) != 4:
            raise InvalidAVPLengthError(avp)
        try:
            value = struct.unpack("!f", avp.payload)[0]
        except struct.error:
            raise InvalidAVPValueError
        a = Float32AVP(avp.code, value, avp.vendorId)
        a.flags = avp.flags
        return a